'''
Created on 07/08/2010

@author: piranna
'''

from . import BLOCK_SIZE,TEST_DRIVE

import sys

def Read(chunks):
    f = file(TEST_DRIVE, "r+b")

    data = ""
    for chunk in chunks:
        if chunk['sector'] != None:
            f.seek(chunk['sector']*BLOCK_SIZE)
            data += f.read(chunk['length']*BLOCK_SIZE)

        else:
            data += '\0'*chunk['length']*BLOCK_SIZE

    f.close()

    return data


def Write(chunks,data, floor):
#    print >> sys.stderr, "Write",repr(data),floor
    f = file(TEST_DRIVE, "r+b")

    for chunk in chunks:
#        print >> sys.stderr, "\t",chunk

        offset = (chunk['block']-floor)*BLOCK_SIZE
        f.seek(chunk['sector']*BLOCK_SIZE)
        f.write(data[offset:offset + chunk['length']*BLOCK_SIZE])

#        print >> sys.stderr, "\t",offset,offset + chunk['length']*BLOCK_SIZE
#        print >> sys.stderr, "\t",chunk['sector']*BLOCK_SIZE,repr(data[offset:offset + chunk['length']*BLOCK_SIZE])

    f.close()